import React from "react";
import { observer, inject } from "mobx-react";
import { withRouter } from "react-router-dom";
import { RichEditor, Button, Tools } from "weaver-mobile";
import { Reply, RouteLayout } from "weaver-mobile-page";
import { asyncComponent } from "react-async-component";
import { CommonText } from "../../../governTools/comText/text";
import ComTextContianer from "../../../governTools/comTextContianer/comTextContianer.js";
const getLabel = Tools.getLabel;
const commonText = new CommonText();
const NoMask = Reply.NoMask;
const ButtonGroup = RouteLayout.ButtonGroup;

const coms = {
  ComProgress: asyncComponent({
    resolve: () => import("../../../governTools/comProgress/comProgress")
  })
};
@inject("editStore")
@withRouter
@observer
/*
 * @info: 评论/汇报编辑组件
 * @Author: lusx
 * @Date: 2019-12-01 11:13:16
 * @Last modified by:   lusx
 * @Last modified time: 01-04-2019 04:07:58
 */
export default class EditPage extends React.Component {
  constructor(props) {
    super(props);
    //this.richRef = React.createRef();
    this.state = {
      height: (document.documentElement.clientHeight * 2) / 5,
      data: "",
      sliderValue: 0
    };
  }
  componentWillMount() {
    const {
      editStore: { setRoutePath }
    } = this.props;
    setRoutePath(this.props.location.pathname);
  }

  render() {
    const {
      history,
      match: {
        params: { editType }
      },
      editStore: { replyStore, sliderValue }
    } = this.props;
    const leftConfig = [
      { type: "blog-biaoqing" },
      { type: "blog-tupian", model: 2 },
      { type: "tianjia" }
    ];
    const PLACEHOLDER = getLabel(
        commonText.PLACEHOLDER[0],
        commonText.PLACEHOLDER[1]
      ),
      PUBLISH = getLabel(commonText.PUBLISH[0], commonText.PUBLISH[1]);
    const btns = [
      {
        key: "clear",
        text: `${getLabel(201, "取消")}`,
        onClick: () => history.go(-1)
      },
      {
        key: "submit",
        text: `${getLabel(615, "提交")}`,
        onClick: () => {
          this.publishAction();
        },
        type: "primary"
      }
    ];
    return (
      <RouteLayout>
        <div
          key="wmPoutePageDemo"
          className="wm-route-layout wm-search-advanced-modal"
        >
          <ComTextContianer
            className="g-editPage ql-editor"
            top={
              <RichEditor
                height={200}
                placeholder={PLACEHOLDER}
                modules={{ toolbar: false }}
                getRef={ref => (this.refObj = ref)}
                onFocus={() => this.replyRef.setVisible(false)}
                data={this.state.data}
                onEditorBlur={this.editorBlur.bind(this)}
              />
            }
            bottom={
              <div>
                {editType === "editReport" && (
                  <coms.ComProgress
                    sliderValue={sliderValue}
                    changeHandle={this.changeHandle.bind(this)}
                  />
                )}
                <NoMask
                  wrappedComponentRef={ref => (this.replyRef = ref)}
                  store={replyStore}
                  showInput={false}
                  leftConfig={leftConfig}
                  onEmojiChange={emoji => this.emojiChange(emoji)}
                  onImgChange={datas => this.imgChange(datas)}
                  onBrowserChange={(key, datas) =>
                    this.browserChange(key, datas)
                  }
                  onUploadChange={(key, datas) => this.uploadChange(key, datas)}
                />
              </div>
            }
          />
          <ButtonGroup data={btns} isButton={true} />
        </div>
      </RouteLayout>
    );
  }
  //富文本失去焦点
  editorBlur() {
    this.setState({
      data: this.refObj.state.value
    });
  }
  //附件
  uploadChange = (key, datas) => {
    datas.map(v => {
      this.insertHTML = `<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${
        v.id
      }" onclick="try{opendoc1('${v.id}',this);return false;}catch(e){}">${
        v.name
      }</a>&nbsp;`;
      this.setState((preState, props) => {
        return { data: `${preState.data}${this.insertHTML}` };
      });
    });
  };
  //流程文档
  browserChange = (key, datas) => {
    datas.map(v => {
      this.insertHTML = `<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${
        v.id
      }" linktype="${key}" onclick="try{return openAppLink(this,${
        v.id
      });}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;`;
      this.setState((preState, props) => {
        return {
          data: `${preState.data}${this.insertHTML}`
        };
      });
    });
  };
  //图片
  imgChange = datas => {
    datas.map(v => {
      this.insertHTML = `<img src=${v.imgSrc} class='mobileBlogImgInnerTemp'/>`;
      this.setState((preState, props) => {
        return { data: `${this.refObj.state.value}${this.insertHTML}` };
      });
    });
  };
  //表情
  emojiChange = emoji => {
    this.insertHTML = `<span>${emoji}</span>`;
    this.setState((preState, props) => {
      return { data: `${preState.data}${this.insertHTML}` };
    });
  };
  //进度条
  changeHandle(v) {
    this.setState({
      sliderValue: v,
      data: this.refObj.props.value
    });
  }
  //发布
  publishAction() {
    const {location,match} = this.props;
    const instructTopid = new URLSearchParams(location.search).get('instructTopid');
    const instructid = new URLSearchParams(location.search).get('instructid');
    this.setState(
      (preState, props) => {
        return { data: this.refObj.props.value };
      },
      () => publishFun()
    ); //19.1.25安卓不支持onBlur事件，采用此办法
    const publishFun = () => {
      const {
        editStore: { publishComment, publishReport },
        location,
        match: {
          params: { editType }
        },
        history: { goBack },
        navTitle
      } = this.props;
      const id = new URLSearchParams(location.search).get("id");
      const params = {
        editComment: {
          instype: "1",
          taskId: id,
          content: this.state.data
        },
        editReport: {
          topic: navTitle,
          taskid: id,
          content: this.refObj.state.value,
          progress: this.state.sliderValue
        },
        editReply1: {//评论
          content: this.state.data,
          taskId: id,
          instype: '3',
          instructTopid: instructTopid,
        },
        editRreply1: {//评论
          content: this.state.data,
          instructid: instructid,
          taskId: id,
          instype: "3",
          instructTopid: instructTopid,
        },
        editReply0: {//汇报
          content: this.state.data,
          taskId: id,
          instype: '2',
          instructTopid: instructTopid,
        },
        editRreply0: {//汇报
          content: this.state.data,
          instructid: instructid,
          taskId: id,
          instype: "2",
          instructTopid: instructTopid,
        },
      };
      if ("editComment editReply1 editRreply1 editReply0 editRreply0".includes(editType)) {
        publishComment({ ...params[editType] }, result => {
          if (result.status === "1") {
            goBack();
          }
        });
      } else if ("editReport".includes(editType)) {
        publishReport({ ...params[editType] }, result => {
          if (result.status === "1") {
            goBack();
          }
        });
      }
    };
  }
}
